package com.mcc.app.productionMat.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mcc.app.cache.service.IPlcCacheService;
import com.mcc.app.group.domain.GroupSche;
import com.mcc.app.group.service.IGroupScheService;
import com.mcc.common.core.text.Convert;
import com.mcc.common.utils.DateUtils;
import com.mcc.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mcc.app.productionMat.mapper.RawMaterialConsumptionMapper;
import com.mcc.app.productionMat.domain.RawMaterialConsumption;
import com.mcc.app.productionMat.service.IRawMaterialConsumptionService;

/**
 * 原料消耗记录Service业务层处理
 *
 * @author gxy
 * @date 2025-03-21
 */
@Service
@Slf4j
public class RawMaterialConsumptionServiceImpl implements IRawMaterialConsumptionService {

    @Autowired
    private RawMaterialConsumptionMapper rawMaterialConsumptionMapper;

    @Autowired
    private IPlcCacheService plcCacheService;

    @Autowired
    private IGroupScheService groupScheService;
    /**
     * 查询原料消耗记录
     *
     * @param id 原料消耗记录ID
     * @return 原料消耗记录
     */
    @Override
    public RawMaterialConsumption selectRawMaterialConsumptionById(Long id) {
        return rawMaterialConsumptionMapper.selectById(id);
    }

    /**
     * 查询原料消耗记录列表
     *
     * @param rawMaterialConsumption 原料消耗记录
     * @return 原料消耗记录
     */
    @Override
    public List<RawMaterialConsumption> selectRawMaterialConsumptionList(RawMaterialConsumption rawMaterialConsumption) {
        QueryWrapper queryWrapper = new QueryWrapper();
        if (ObjectUtil.isNotEmpty(rawMaterialConsumption)) {
            queryWrapper.eq(ObjectUtil.isNotEmpty(rawMaterialConsumption.getRawDate()), "raw_date", rawMaterialConsumption.getRawDate());
            queryWrapper.ge(ObjectUtil.isNotEmpty(rawMaterialConsumption.getBeginDate()),"raw_date",rawMaterialConsumption.getBeginDate());
//查询条件：小于 le（条件，作用对象，值），让日期小于结束时间
            queryWrapper.le(ObjectUtil.isNotEmpty(rawMaterialConsumption.getEndDate()),"raw_date",rawMaterialConsumption.getEndDate());

            queryWrapper.like(ObjectUtil.isNotEmpty(rawMaterialConsumption.getMatterName()), "matter_name", rawMaterialConsumption.getMatterName());
            queryWrapper.like(ObjectUtil.isNotEmpty(rawMaterialConsumption.getClassesName()), "classes_name", rawMaterialConsumption.getClassesName());
            queryWrapper.like(ObjectUtil.isNotEmpty(rawMaterialConsumption.getTeamName()), "team_name", rawMaterialConsumption.getTeamName());
            queryWrapper.eq(ObjectUtil.isNotEmpty(rawMaterialConsumption.getDateType()), "date_type", rawMaterialConsumption.getDateType());
            queryWrapper.eq(ObjectUtil.isNotEmpty(rawMaterialConsumption.getConsumption()), "consumption", rawMaterialConsumption.getConsumption());
            queryWrapper.eq(ObjectUtil.isNotEmpty(rawMaterialConsumption.getConsumptionCost()), "consumption_cost", rawMaterialConsumption.getConsumptionCost());
        }
        queryWrapper.orderByDesc("raw_date");
        return rawMaterialConsumptionMapper.selectList(queryWrapper);
    }

    /**
     * 新增原料消耗记录
     *
     * @param rawMaterialConsumption 原料消耗记录
     * @return 结果
     */
    @Override
    public int insertRawMaterialConsumption(RawMaterialConsumption rawMaterialConsumption) {
        rawMaterialConsumption.setCreateTime(new Date());
//        rawMaterialConsumption.setCreateBy(SecurityUtils.getUsername());
        return rawMaterialConsumptionMapper.insert(rawMaterialConsumption);
    }

    /**
     * 修改原料消耗记录
     *
     * @param rawMaterialConsumption 原料消耗记录
     * @return 结果
     */
    @Override
    public int updateRawMaterialConsumption(RawMaterialConsumption rawMaterialConsumption) {
        rawMaterialConsumption.setUpdateTime(new Date());
//        rawMaterialConsumption.setUpdateBy(SecurityUtils.getUsername());
        return rawMaterialConsumptionMapper.updateById(rawMaterialConsumption);
    }

    /**
     * 删除原料消耗记录
     *
     * @param id 原料消耗记录ID
     * @return 结果
     */
    @Override
    public int deleteRawMaterialConsumptionById(Long id) {
        return rawMaterialConsumptionMapper.deleteById(id);
    }

    /**
     * 批量删除原料消耗记录
     *
     * @param ids 原料消耗记录ID
     * @return 结果
     */
    @Override
    public int deleteRawMaterialConsumptionByIds(Long[] ids) {
        if (ids.length == 0) return 0;
        return rawMaterialConsumptionMapper.deleteBatchIds(ListUtil.toList(ids));
    }

    @Override
    public Map<String, Object>  geMatrialName(){

        Map<String, Object> res = new HashMap<>();
        String nameHeadString = "st2_ingredient";
        String nameTailString = "_name";
        String dailyHeadString = "st2_daily";
        String dailyTailString = "_total";
        for(int i = 1;i<=22;i++){
            String nameString = nameHeadString +Integer.toString(i)+nameTailString;
            String materialName = Convert.toStr(plcCacheService.getRedisCache(nameString));//物料名称
            String dailyString  = dailyHeadString+Integer.toString(i)+dailyTailString;
            res.put(dailyString, materialName);
             }

        return res;
    }

    @Override
    public Map<String, List<Object>>  getHisMatrialByDate(String tableTag, Integer timeTag, Date startDt, Date endDt){

        List<Map<String, Object>> res = plcCacheService.getHisRowByDate("st2", 3, startDt, endDt);//后期可以处理，比如相同物料的数据进行合并
        Map<String, List<Object>> result = new HashMap<>();//key为物料名称和时间 value为数值
//        Map<String, Object> materialMap = new HashMap<>();
        Map<String,List<String>> nameDailyMap = new HashMap<>();//物料名 料仓列表  可能存在不同的料仓同样得物料名称

        String nameHeadString = "st2_ingredient";
        String nameTailString = "_name";
        String dailyHeadString = "st2Daily";
        String dailyTailString = "Total";
//        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        for(int i = 1;i<=23;i++){
            String nameString = nameHeadString +Integer.toString(i)+nameTailString;
            String materialName = Convert.toStr(plcCacheService.getRedisCache(nameString));//物料名称
//            log.info("materialName is "+materialName);
            String dailyString  = dailyHeadString+Integer.toString(i)+dailyTailString;
//            materialMap.put("st2Daily"+i+"Total", materialName);
            if(nameDailyMap.containsKey(materialName)){
                List<String> stockList = nameDailyMap.get(materialName);
                stockList.add(dailyString);
            }else{
                List<String> stockList = new ArrayList<>();
                stockList.add(dailyString);
                nameDailyMap.put(materialName, stockList);
            }
        }
       for(int i = 0;i<res.size();i++){
           Map<String, Object> map = res.get(i);
           if(result.containsKey("dt")){
               List<Object> values = result.get("dt");
               values.add(map.get("dt"));
           }else{
               List<Object> values = new ArrayList<>();
               values.add(map.get("dt"));
               result.put("dt", values);
           }
           for (Map.Entry<String, List<String>> entry : nameDailyMap.entrySet())
           {
               //首先对相同物料数据进行料仓数据合并
               List<String> stockList = entry.getValue();
               Double totalValue = 0.0;
               for(int j = 0; j<stockList.size();j++){
                   String daily = stockList.get(j);
                   Object value = map.get(daily);
                   if(value != null){
                       totalValue += Convert.toDouble(value);
                   }
               }
               //将合并后得数据填入对应得返回列表中
               if(result.containsKey(entry.getKey())){
                   List<Object> values = result.get(entry.getKey());
                   values.add(totalValue);
               }else{
                   List<Object> values = new ArrayList<>();
                   values.add(totalValue);
                   result.put(entry.getKey(), values);
               }
           }
       }

        log.info("result is "+result);
        return result;
    }

    @Override
    public RawMaterialConsumption selectRawMaterialConsumptionByCond(RawMaterialConsumption rawMaterialConsumption){
        QueryWrapper queryWrapper = new QueryWrapper();
        if (ObjectUtil.isNotEmpty(rawMaterialConsumption)) {
            queryWrapper.eq(ObjectUtil.isNotEmpty(rawMaterialConsumption.getRawDate()), "raw_date", rawMaterialConsumption.getRawDate());
            queryWrapper.eq(ObjectUtil.isNotEmpty(rawMaterialConsumption.getMatterName()), "matter_name", rawMaterialConsumption.getMatterName());
            queryWrapper.eq(ObjectUtil.isNotEmpty(rawMaterialConsumption.getClassesName()), "classes_name", rawMaterialConsumption.getClassesName());
            queryWrapper.eq(ObjectUtil.isNotEmpty(rawMaterialConsumption.getTeamName()), "team_name", rawMaterialConsumption.getTeamName());
            queryWrapper.eq(ObjectUtil.isNotEmpty(rawMaterialConsumption.getDateType()), "date_type", rawMaterialConsumption.getDateType());
        }
        queryWrapper.last("limit 1");
        return rawMaterialConsumptionMapper.selectOne(queryWrapper);
    }
    @Override
    public List<RawMaterialConsumption> getCurrentMaterialList(RawMaterialConsumption rawMaterialConsumption)
    {
        List<RawMaterialConsumption> resultList = new LinkedList<>();
        Date date = new Date();
        GroupSche groupSche = groupScheService.getGroupScheByDt(date);
        if (null == groupSche) {
            return null;
        }
        //直接获取plc_cache中班次统计值
        if(groupSche.getClassesId() == 1){//只考虑当前班次

        }else if(groupSche.getClassesId() == 2){//需要考虑当前和前一班次

            Date groupDate = DateUtil.offsetHour(date, -8);//为准确获取当前结束得是哪个班次

        }else if(groupSche.getClassesId() == 3){//需要考虑当前、前一和前二班次

            Date b1GroupDate = DateUtil.offsetHour(date, -8);//为准确获取当前结束得是哪个班次

            Date b2GroupDate = DateUtil.offsetHour(b1GroupDate, -8);//为准确获取当前结束得是哪个班次
        }

        return resultList;

    }
}
